import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const permissions = ref([])
  const roles = ref([])

  const isLoggedIn = computed(() => !!token.value)

  const login = async (username, password) => {
    try {
      const response = await authApi.login(username, password)
      user.value = response.data
      token.value = response.data.token || 'mock-token'
      localStorage.setItem('token', token.value)
      
      // 获取用户权限和角色
      await Promise.all([
        loadPermissions(),
        loadRoles()
      ])
      
      return response
    } catch (error) {
      throw error
    }
  }

  const logout = async () => {
    try {
      if (user.value?.id) {
        await authApi.logout(user.value.id)
      }
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      user.value = null
      token.value = ''
      permissions.value = []
      roles.value = []
      localStorage.removeItem('token')
    }
  }

  const loadPermissions = async () => {
    if (user.value?.id) {
      try {
        const response = await authApi.getPermissions(user.value.id)
        permissions.value = response.data
      } catch (error) {
        console.error('获取权限失败:', error)
      }
    }
  }

  const loadRoles = async () => {
    if (user.value?.id) {
      try {
        const response = await authApi.getRoles(user.value.id)
        roles.value = response.data
      } catch (error) {
        console.error('获取角色失败:', error)
      }
    }
  }

  const checkPermission = async (permissionName) => {
    if (!user.value?.id) return false
    try {
      const response = await authApi.checkPermission(user.value.id, permissionName)
      return response.data
    } catch (error) {
      console.error('检查权限失败:', error)
      return false
    }
  }

  const checkRole = async (roleName) => {
    if (!user.value?.id) return false
    try {
      const response = await authApi.checkRole(user.value.id, roleName)
      return response.data
    } catch (error) {
      console.error('检查角色失败:', error)
      return false
    }
  }

  return {
    user,
    token,
    permissions,
    roles,
    isLoggedIn,
    login,
    logout,
    loadPermissions,
    loadRoles,
    checkPermission,
    checkRole
  }
}) 